﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    public class IfParser : ILineParser
    {
        private static readonly Regex IfPattern =
            new Regex(
                @"(?<=^If )(?<condition>.+) Then( (?<body>.+))?",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        private static readonly Regex EqualOp =
            new Regex(
                @" = ",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            var match = IfPattern.Match(lineContent);
            success = match.Success;
            if (!success) return lineContent;
            var condition = EqualOp.Replace(match.Groups["condition"].Value, " == ");
            var appendB = false;
            if (!string.IsNullOrEmpty(match.Groups["body"].Value))
            {
                //var pos = reader.CurrentLine;
                //var comments = new StringBuilder();
                //var next = ConvertEngine.ReadNextNotEmptyLine(reader, comments);
                //if (next != "End If")
                //{
                //    appendB = true;
                //}
                //reader.CurrentLine = pos;
                appendB = true;
            }
            if (!appendB)
            {
                statuses.Push(new ParseStatus() { CurrentState = State.IfDef });
            }
            if (lineClosed)
            {
                throw new Exception();
            }
            lineClosed = true;
            return string.Format("if ({0}) {{ {1}{2}", condition, ParserHelper.ResolveFunctionCall(match.Groups["body"].Value), appendB ? ";}" : "");
        }
    }
}
